package middleware

import (
	"errors"
	"github.com/gofiber/fiber/v2"
	"strings"
	"zatta-gateway/http/types"
	"zatta-gateway/http/utils"
)

func UserJWTAuth() fiber.Handler {
	return func(c *fiber.Ctx) error {
		authHeader := c.Get(fiber.HeaderAuthorization)
		if authHeader == "" {
			return c.Status(fiber.StatusUnauthorized).SendString("Authorization header user_jwt is missing")
		}
		var userJWT string
		if len(authHeader) > 7 && authHeader[:7] == types.AuthorizationPrefix {
			userJWT = strings.TrimSpace(authHeader[7:])
		} else {
			return c.Status(fiber.StatusUnauthorized).SendString("Invalid Authorization header")
		}

		claims, err := utils.ParseToken(userJWT, utils.DefaultJWTConfig)
		if err != nil {
			if errors.Is(err, utils.ErrTokenExpired) {
				return c.Status(fiber.StatusUnauthorized).SendString("User JWT is expired")
			}
			return c.Status(fiber.StatusUnauthorized).SendString("Invalid User JWT")
		}

		c.Locals("user_jwt", userJWT)
		c.Locals("user_claims", claims)
		return c.Next()
	}
}
